package com.houduan.controller;

import com.houduan.dao.ComputerDao;
import com.houduan.dao.SessionDao;
import com.houduan.dao.UserDao;
import com.houduan.model.Computer;
import com.houduan.model.Session;
import com.houduan.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class SessionServlet extends HttpServlet {

    private SessionDao sessionDao = new SessionDao();
    private ComputerDao computerDao = new ComputerDao();
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "start":
                startSession(request, response);
                break;
            case "end":
                endSession(request, response);
                break;
            default:
                response.sendRedirect("SessionServlet?action=list");
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "list":
                listSessions(request, response);
                break;
            case "filterByType":
                filterByType(request, response);
                break;
            default:
                response.sendRedirect("SessionServlet?action=list");
                break;
        }
    }

    // 开始上机
    private void startSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int userId = Integer.parseInt(request.getParameter("userId"));
            int computerId = Integer.parseInt(request.getParameter("computerId"));
            int duration = Integer.parseInt(request.getParameter("duration")); // 获取上机时长

            User user = userDao.getUserById(userId);
            Computer computer = computerDao.getComputerById(computerId);

            if (user == null) {
                response.sendRedirect("session_management.jsp?error=用户不存在");
                return;
            }

            if (computer == null || !"空闲".equals(computer.getStatus())) {
                response.sendRedirect("session_management.jsp?error=电脑不可用");
                return;
            }

            // 创建新的上机记录
            Session session = new Session(0, user, computer, null, null, 0, 0);
            sessionDao.startSession(session);

            // 更新电脑状态为“使用中”
            computerDao.updateStatus(computerId, "使用中");

            // 设置定时任务，在时长结束后自动下机
            int sessionId = sessionDao.getLastSessionId(); // 获取刚插入的会话 ID
            scheduleEndSession(sessionId, duration);

            response.sendRedirect("SessionServlet?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("session_management.jsp?error=开始上机失败");
        }
    }

    // 定时任务：在指定时长后自动下机
    private void scheduleEndSession(int sessionId, int duration) {
        new java.util.Timer().schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                try {
                    Session session = sessionDao.getSessionById(sessionId);

                    if (session != null && session.getEndTime() == null) {
                        // 自动结束上机
                        double duration = sessionDao.calculateDuration(sessionId);
                        double cost = duration * session.getComputer().getPrice();

                        sessionDao.endSession(sessionId, duration, cost);
                        userDao.updateBalance(session.getUser().getId(), -cost);
                        computerDao.updateStatus(session.getComputer().getId(), "空闲");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, duration * 60 * 1000L); // 转换为毫秒
    }
    // 提前下机
    private void endSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            int sessionId = Integer.parseInt(request.getParameter("sessionId"));
            Session session = sessionDao.getSessionById(sessionId);

            if (session == null || session.getEndTime() != null) {
                response.sendRedirect("session_management.jsp?error=无效的上机记录");
                return;
            }

            // 计算使用时长和费用
            double duration = sessionDao.calculateDuration(sessionId);
            double cost = duration * session.getComputer().getPrice();

            // 更新上机记录
            sessionDao.endSession(sessionId, duration, cost);

            // 更新用户余额
            userDao.updateBalance(session.getUser().getId(), -cost);

            // 更新电脑状态为“空闲”
            computerDao.updateStatus(session.getComputer().getId(), "空闲");

            response.sendRedirect("SessionServlet?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("session_management.jsp?error=提前下机失败");
        }
    }

    // 显示所有上机记录
    private void listSessions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Session> sessions = sessionDao.getAllSessions();

            // 计算实时时长和费用
            for (Session session : sessions) {
                if (session.getEndTime() == null) { // 如果未结束，实时计算
                    session.setDuration(session.calculateDuration());
                    session.setCost(session.calculateCost());
                }
            }

            request.setAttribute("sessions", sessions);
            request.getRequestDispatcher("session_management.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("session_management.jsp?error=加载上机记录失败");
        }
    }


    // 按型号筛选空闲电脑
    private void filterByType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String type = request.getParameter("type"); // 获取用户选择的型号
            List<Computer> freeComputers;

            if (type == null || type.isEmpty()) {
                // 如果没有指定型号，则查询所有空闲电脑
                freeComputers = computerDao.getFreeComputers();
            } else {
                // 根据型号查询空闲电脑
                freeComputers = computerDao.getFreeComputersByType(type);
            }

            // 获取所有型号供用户选择
            List<String> computerTypes = computerDao.getAllComputerTypes();

            // 将数据传递到 JSP 页面
            request.setAttribute("freeComputers", freeComputers);
            request.setAttribute("computerTypes", computerTypes);
            request.getRequestDispatcher("session_management.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("session_management.jsp?error=筛选电脑失败");
        }
    }
}
